/* eslint-disable camelcase */
/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import { message, Spin } from 'antd';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import NewNodeCard from './components/new-node-card';
import buyClusterImg from '../images/buy-cluster.png';
import { getNodeList } from '@api/nodes';
import _ from 'lodash';
import './index.less';

const prefixCls = 'node-manage';

class NodeManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ips: [],
      list: [],
      spinning: false,
      statusList: []
    };
    this.pollingTimer = null;
  }
  componentDidMount() {
    this.getNodeList();
  }

  getNodeList = () => {
    getNodeList()
      .then(res => {
        const list = _.get(res, 'data.data', []);
        this.setState({
          list: list.sort(node => (node.node_role === 'master' ? -1 : 1))
        });
        const { hasCluster, cert } = this.props;
        // 如果是单机，集群列表一定为空，取证书的信息
        // 如果是集群，集群列表为空，说明是集群组装前，取证书的信息
        if (!hasCluster || (hasCluster && list.length === 0)) {
          const { local_node_ip, now } = cert;
          this.setState({
            list: [
              {
                node_role: 'single',
                boot_time: now,
                node_ip: local_node_ip,
                status: 'online'
              }
            ]
          });
        }
      })
      .catch(() => {
        message.error('获取列表失败');
      });
  };

  render() {
    const { list, spinning } = this.state;
    const { hasCluster } = this.props;

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>节点管理</div>
        <Spin spinning={spinning} wrapperClassName="spin-wrapper">
          <div className={`${prefixCls}-content`}>
            {/* 集群显示这个 */}
            {hasCluster && <NewNodeCard list={list} onOk={this.getNodeList} singer={!hasCluster} />}
            {/* 单机显示这个 */}
            {!hasCluster && (
              <div className="buy-cluster new-node-card ">
                <img src={buyClusterImg} />
                <div>
                  <span>购买集群增值服务，添加更多设备</span>
                </div>
              </div>
            )}
          </div>
        </Spin>
      </div>
    );
  }
}

NodeManage.propTypes = {
  cert: PropTypes.object,
  hasCluster: PropTypes.bool
};

const mapStateToProps = state => {
  return {
    cert: _.get(state, 'auth.cert', {}),
    hasCluster: _.includes(state?.auth?.cert?.modules, 'distribute')
  };
};

export default connect(mapStateToProps)(NodeManage);
